/**
 * Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights
 * Reserved. MIT License  (https://opensource.org/licenses/MIT)
 */
/* 2021-2023 by zhaoming,mali aihealthx.com */

function WebSocketConnectMethod(config) {
	//定义socket连接方法类

	let speechSocket;
	let connKeeperID;

	const msgHandle = config.msgHandle;
	const stateHandle = config.stateHandle;
	const wsUrl = config.wsUrl;
	this.wsStart = function () {
		if (wsUrl.match(/wss:\S*|ws:\S*/)) {
			console.log('Uri' + wsUrl);
		} else {
			alert('请检查wss地址正确性');
			return 0;
		}

		if ('WebSocket' in window) {
			speechSocket = new WebSocket(wsUrl); // 定义socket连接对象
			speechSocket.onopen = function (e) {
				onOpen(e);
			}; // 定义响应函数
			speechSocket.onclose = function (e) {
				console.log('onclose ws!');
				onClose(e);
			};
			speechSocket.onmessage = function (e) {
				onMessage(e);
			};
			speechSocket.onerror = function (e) {
				onError(e);
			};
			return 1;
		} else {
			alert('当前浏览器不支持 WebSocket');
			return 0;
		}
	};

	// 定义停止与发送函数
	this.wsStop = function () {
		if (speechSocket != undefined) {
			console.log('stop ws!');
			speechSocket.close();
		}
	};

	this.wsSend = function (oneData) {
		if (speechSocket == undefined) return;
		if (speechSocket.readyState === 1) {
			// 0:CONNECTING, 1:OPEN, 2:CLOSING, 3:CLOSED

			speechSocket.send(oneData);
		}
	};

	// Socket连接中的消息与状态响应
	function onOpen(e) {
		// 发送json
		let chunk_size = new Array(5, 10, 5);
		let request = {
			chunk_size: chunk_size,
			wav_name: 'h5',
			is_speaking: true,
			chunk_interval: 10,
			itn: getUseITN(),
			mode: getAsrMode()
		};
		if (window.wsConfig.isFileMode) {
			request.wav_format = window.wsConfig.file_ext;
			if (file_ext == 'wav') {
				request.wav_format = 'PCM';
				request.audio_fs = file_sample_rate;
			}
		}

		const hotwords = getHotwords();

		if (hotwords != null) {
			request.hotwords = hotwords;
		}
		console.log(JSON.stringify(request));
		speechSocket.send(JSON.stringify(request));
		console.log('连接成功');
		stateHandle(0);
	}

	function onClose(e) {
		stateHandle(1);
	}

	function onMessage(e) {
		msgHandle(e);
	}

	function onError(e) {
		console.log(e);
		stateHandle(2);
	}
}

window.WebSocketConnectMethod = WebSocketConnectMethod;
